package com.xxy.shiro.controller;


import com.xxy.shiro.entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller
public class ShiroController {


    /**
     * 去首页
     *
     * @return
     */
    @RequestMapping("/index")
    public String toIndex() {
        return "index";
    }

    /**
     * 主页
     *
     * @return
     */
    @RequestMapping("/home")
    public String home() {
        return "home";
    }

    /**
     * 首页
     *
     * @return
     */
    @RequestMapping("/")
    public String index() {
        return "index";
    }

    @RequestMapping("/login")
    public String toLogin() {
        return "login";
    }


    /**
     * 登录逻辑处理
     *
     * @return
     */
    @PostMapping("/login")
    public String login(String username, String password, Model model) {
        // 使用 SecurityUtils 得到主体
        Subject subject = SecurityUtils.getSubject();
        // 生成令牌
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        try {
            System.out.println("===========");
            subject.login(token);
            System.out.println("---------");
            return "redirect:/home";
        } catch (UnknownAccountException e) {
            //e.printStackTrace();
            model.addAttribute("msg", "用户名错误!");
        }catch (IncorrectCredentialsException e){
            //e.printStackTrace();
            model.addAttribute("msg","密码错误!");
        }
        return "login";
    }

    /**
     * 注销
     * @return
     */
    @RequestMapping("/logout")
    public String logout(){
        SecurityUtils.getSubject().logout();
        return "index";
    }
}
